package com.example.cwproject.service.serviceImpl;


import com.example.cwproject.entity.Email;
import com.example.cwproject.entity.User;
import com.example.cwproject.exception.ServiceException;
import com.example.cwproject.mapper.EmailMapper;
import com.example.cwproject.mapper.UserMapper;
import com.example.cwproject.service.EmailService;
import com.example.cwproject.utils.CharUtils;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    UserMapper userMapper;

    @Autowired
    EmailMapper emailMapper;

    @Override
    public String sendEmail(String email){

        // 查看注册邮箱是否存在
        User dbUser = userMapper.selectReturnUser(email);
        if(dbUser != null){
            throw new ServiceException("邮箱已注册");
        }

        // 获取随机6位验证码
        String verify = CharUtils.randomVerify();

        //将邮箱和对应验证码保存在数据库email表中
        Email emailSave = emailMapper.selectAllByEmail(email);
        if(emailSave != null){
            emailMapper.updateVerifyCode(emailSave.getEmail(),verify);
        } else{
            Email emailSave2 = new Email();
            emailSave2.setEmail(email);
            emailSave2.setVerifyCode(verify);
            emailMapper.insert(emailSave2);
        }

        SimpleMailMessage message = new SimpleMailMessage();
        // 发送邮箱
        message.setFrom(username);
        // 接受邮箱
        message.setTo(email);
        // 标题
        message.setSubject("安全服务平台-邮箱验证");
        // 内容
        message.setText("尊敬的用户您好：\n" +
                "您正在进行邮箱验证，本次验证码为：" + verify + "，请在10分钟内进行使用。\n" +
                "如非本人操作，请忽略此邮件，由此给您带来的不便请谅解！\n--安全服务平台");

        mailSender.send(message);

        return verify;

    }
}

